import { FC, useState } from 'react';
import { Popover, Input, InputProps, Form, Space, Button } from 'antd';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { ProFormFieldItemProps } from '@ant-design/pro-form/lib/interface';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { SearchOutlined } from '@ant-design/icons';
import './index.less';
import { useForm } from 'antd/lib/form/Form';

type SelectTablePickerProps = {
  title?: string;
  columns: ProColumns<Record<string, any>, 'text'>[];
  valueName: string;
  request: (param: any) => Promise<any>;
  params?: Record<string, any>;
  onSelected?: (record: Record<string, any>) => void;
  value?: string;
  formatter?: (recode: Record<string, any>) => string;
  onChange?: (value: string) => void;
} & ProFormFieldItemProps<InputProps>;

const SelectTablePicker: FC<SelectTablePickerProps> = (props) => {
  const [isPopoverVisible, setIsPopoverVisible] = useState(false);
  const [reqParam, setReqParam] = useState<Record<string, any> | undefined>(props.params);
  const [form] = useForm();

  function getPickerContent(setFieldsValue: (value: any) => void) {
    return (
      <>
        <div className="selectTablePicker">
          <ProForm form={form} layout="horizontal" submitter={false} className="tableSearch">
            <Space>
              {props.columns
                .filter((column) => column.search !== false)
                .map((column) => {
                  return <ProFormText label={column.title} name={column.dataIndex} />;
                })}

              <Button
                type="primary"
                icon={<SearchOutlined />}
                ghost
                onClick={() => {
                  setReqParam({
                    ...props.params,
                    ...form.getFieldsValue(),
                    _r: new Date().getTime(),
                  });
                }}
              >
                查询
              </Button>
            </Space>
          </ProForm>
        </div>
        <ProTable
          size="small"
          bordered
          style={{ maxWidth: '800px' }}
          scroll={{
            x: 'max-content',
          }}
          rowKey={props.valueName}
          search={false}
          toolBarRender={false}
          columns={props.columns}
          pagination={{ pageSize: 5, showSizeChanger: false }}
          request={props.request}
          params={reqParam}
          onRow={(record) => {
            return {
              onDoubleClick: () => {
                setIsPopoverVisible(false);
                const fieldValue = props.formatter
                  ? props.formatter(record)
                  : record[props.valueName];
                setFieldsValue({ [props.name as string]: fieldValue });
                props.onChange && props.onChange(fieldValue);
                props.onSelected && props.onSelected(record);
              },
            };
          }}
        />
      </>
    );
  }

  return (
    <Form.Item noStyle shouldUpdate={true}>
      {({ setFieldsValue }) => (
        <Form.Item {...props} className="selectTablePicker">
          <Input
            className="searchInput"
            value={props.value}
            onChange={(e) => {
              props.onChange && props.onChange(e.target.value);
            }}
            addonAfter={
              <Popover
                placement="bottom"
                trigger="click"
                autoAdjustOverflow
                title={props.title}
                content={getPickerContent(setFieldsValue)}
                visible={isPopoverVisible}
                onVisibleChange={(visible) => {
                  setIsPopoverVisible(visible);
                }}
              >
                <SearchOutlined style={{ padding: '5px 11px' }} />
              </Popover>
            }
          />
        </Form.Item>
      )}
    </Form.Item>
  );
};

export default SelectTablePicker;
